package com.zt.ztrob.task;

import java.util.Iterator;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.blade.kit.DateKit;
import com.blade.kit.StringKit;
import com.blade.kit.http.HttpRequest;
import com.zt.ztrob.api.MsgAPI;
import com.zt.ztrob.api.TulingAPI;
import com.zt.ztrob.bean.Wechat;
import com.zt.ztrob.bean.WechatContact;
import com.zt.ztrob.bean.WechatQun;
import com.zt.ztrob.common.UserContext;
import com.zt.ztrob.service.WechatBotService;
import com.zt.ztrob.utils.Constant;
import com.zt.ztrob.utils.GetGroupNickName;

public class HandleMsgTask implements Runnable {

	private static final Logger logger = LoggerFactory.getLogger(HandleMsgTask.class);
	private WechatBotService wechatBotService = new WechatBotService();
	private Wechat wechat;
	private WechatContact wContact;
	private static int threadCount = 0;
	private WechatQun wechatqun = new WechatQun();
	private int count=1;

	public HandleMsgTask() {
		this.wechat = UserContext.getWechat();
		this.wContact = wechatBotService.getContact();
		
	}

	@Override
	public void run() {
		HandleMsgTask.threadCount = threadCount + 1;
		String status=wContact.getRobStatus();
		logger.info("wbot thread count:{}", threadCount);
		logger.info("sync check:[{}][{}]", wechat.getUser().getString("NickName"),
				wechat.getUser().getString("UserName"));
		while (true) {
			/**
			 * 监测心跳 默认为[-1,-1](请求异常) synccheck[0]：0 正常，1100 失败/登出微信
			 * synccheck[1]：0 正常，2 新的消息，7 进入/离开聊天界面
			 */
			int[] synccheck = wechatBotService.synccheck(wechat);

			// 请求异常
			if (synccheck[0] == -1) {
				logger.info("请求异常：sync check error:[{}][{}]", wechat.getUser().getString("NickName"),
						wechat.getUser().getString("UserName"));
				break;

			}
			// 失败/登出微信
			if (synccheck[0] == 1100 || synccheck[0] == 1101) {
				wxlogout(wechat.getWxuin());
				logger.info("失败/登出微信login out:[{}][{}]", wechat.getUser().getString("NickName"),
						wechat.getUser().getString("UserName"));
				break;
			}
			// 正常
			if(status.equals("1")){
				if (synccheck[0] == 0) {
					switch (synccheck[1]) {
					case 0: // 正常
						break;
					case 2: { // 新的消息
						JSONObject object = this.webwxsync(wechat);
						this.handleMsg(wechat, object, wContact);
						break;
					}
					case 3:
						break;
					case 6: {
						JSONObject object = this.webwxsync(wechat);
						this.handleMsg(wechat, object, wContact);
						break;
					}
					case 7: // 进入/离开聊天界面
						break;
					}
				}
			}
			if(!status.equals("1")){
				logger.info("新注册用户，无此权限");
				break;
			}
			try {
				Thread.sleep(3000); // 等待2s
			} catch (InterruptedException e) {
			}
		}
		threadCount = threadCount - 1;
	}

	/**
	 * 获取消息
	 */
	private JSONObject webwxsync(Wechat wechat) {
		String url = wechat.getBase_uri() + "/webwxsync?" + "skey=" + wechat.getSkey() + "&sid=" + wechat.getWxsid();
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("BaseRequest", wechat.getBaseRequest());
		jsonObject.put("SyncKey", wechat.getSyncKey());
		jsonObject.put("rr", DateKit.getCurrentUnixTime());
		HttpRequest request = HttpRequest.post(url).contentType(Constant.CONTENT_TYPE)
				.header("Cookie", wechat.getCookie()).send(jsonObject.toString());
		
		//System.out.println("监听信息："+url);//监听信息
		System.out.println("消息监听请求request:"+request);
		String res = request.body();
		//System.out.println("监听到的消息："+res);
		request.disconnect();
		//wechatBotService.getGroup();
		

		JSONObject object = JSON.parseObject(res);
		//System.out.println("object"+object);
		if(object.getString("AddMsgCount").equals("0")){
			//把第一次监听到的群信息放到bean里
			JSONArray modContactList=JSON.parseArray(object.getString("ModContactList"));
			if(wechatqun.getModContactList()==null){
				
			wechatqun.setModContactList(modContactList);
			}
			}
		//System.out.println(object);
		if (null != object) {
			JSONObject BaseResponse = (JSONObject) object.get("BaseResponse");
			if (null != BaseResponse) {
				int ret = BaseResponse.getInteger("Ret");
				if (ret == 0) {
					wechat.setSyncKey(object.getJSONObject("SyncKey"));
					StringBuilder buffer = new StringBuilder();
					JSONArray array = (JSONArray) wechat.getSyncKey().get("List");
					for (Object anArray : array) {
						JSONObject item = (JSONObject) anArray;
						buffer.append("|").append(item.getInteger("Key")).append("_").append(item.getInteger("Val"));
					}
					wechat.setSyncKeyStr(buffer.toString().substring(1));
				}
			}
		}
		try {//把发送信息的参数存到数据库
			if(count>0){
			String sendParam="{\"Base_uri\":"+"\""+wechat.getBase_uri()+"\","+
					"\"PassTicket\":"+"\""+wechat.getPassTicket()+"\","+
					"\"UserName\":"+"\""+wechat.getUser().getString("UserName")+"\","+
					"\"BaseRequest\":"+wechat.getBaseRequest()+
					",\"Cookie\":"+"\""+wechat.getCookie()+"\""+"}";
			HttpRequest setWechatReq=HttpRequest.post(Constant.ROBURL+"sendMsgManage.do?method=addSendParam&uin="+wechat.getWxuin()+"&sendParam="+sendParam);
			System.out.println(setWechatReq.body());
			setWechatReq.disconnect();
			count--;
			}
		} catch (Exception e) {
			return object;
		}
		//System.out.println("object:"+object);
		return object;
	}

	/**
	 * 消息处理
	 */
	private void handleMsg(Wechat wechat, JSONObject msgJson, WechatContact wechatContact) {
		if (wechat != null && msgJson != null) {
			/** 用户ID **/
			String userName = wechat.getUser().getString("UserName");
			/** 消息列表 **/
			JSONArray addMsgList = msgJson.getJSONArray("AddMsgList");
			JSONArray groupList=wechatContact.getGroupList();
			//System.out.println("groupList:"+groupList);
			JSONArray modContactList=wechatqun.getModContactList();
			//System.out.println("群列表："+groupList);
			

			// 遍历消息列表
			for (Object anAddMsgList : addMsgList) {
				JSONObject msg = (JSONObject) anAddMsgList;
				/** 消息类型 **/
				int msgType = (int) msg.get("MsgType");
				/** 发送消息用户ID **/
				String fromUserName = msg.getString("FromUserName");
				/** 接收消息用户ID **/
				// String toUserName = msg.getString("ToUserName");
				/** 消息内容 **/
				String content = msg.getString("Content");
				/** 消息时间 **/
				String groupNickName=new GetGroupNickName().getNickName(groupList, fromUserName);
				/**获取群昵称**/
				// String createTime = msg.getString("CreateTime");
				// 初始化消息
				if (msgType == 51) {
				}
				// 音乐分享--点赞
				if (msgType == 49) {
					// logger.info("音乐分享...");
				}
				// 图片消息
				else if (msgType == 3) {
					// logger.info("图片消息...");
				}
				// 语音消息
				else if (msgType == 34) {
					// logger.info("语音消息...");
				}
				// 动画表情
				else if (msgType == 42) {
					// logger.info("动画表情...");
				}
				// 系统消息
				else if (msgType == 10000) {
					logger.info("系统消息.........");
					//String sendMsg = content.split(":")[1];
					System.out.println(content);
					String welcome=getWelcome(groupNickName)==null?"来到本群":getWelcome(groupNickName);
					if(content.contains("加入了群聊")&&content.contains("邀请")){
						content=content.replaceAll("加入了群聊", "");
						content=content.replaceAll("\"", "");
						String newuser=content.substring(content.indexOf("邀请")+2);
						String reply="欢迎新用户"+newuser+welcome;
						this.sendMsg(wechat, reply, fromUserName);
					}else if(content.contains("加入了群聊")&&content.contains("扫描")){
						content=content.replaceAll("分享的二维码加入了群聊", "");
						content=content.replaceAll("\"", "");
						String newuser=content.substring(content.indexOf("扫描")+2);
						String reply="欢迎新用户"+newuser+welcome;
						this.sendMsg(wechat, reply, fromUserName);
					}
					//logger.info("msg:{}", sendMsg);
				}
				// 文本消息
				else if (msgType == 1) {
					String nickName = this.getNickName(wechat, fromUserName, wechatContact);
					// 自己
					if (fromUserName.equals(userName)) {
						
					// 特殊号
					} else if (Constant.FILTER_USERS.contains(fromUserName)) {
					// 群聊
					} else if (fromUserName.contains("@@")) {
						String groupInf=new GetGroupNickName().getGroupCountAndOwner(groupNickName,modContactList, fromUserName);
						System.out.println("groupInf:"+groupInf+"\n"+groupNickName);
						//System.out.println("======群名字："+groupNickName);
						String sendUserName = content.split(":")[0];
						String sendUserNickName = this.getNickName(wechat, sendUserName, wechatContact);
						String sendMsg = content.split(":")[1];
						//if (sendMsg.contains("@" + wechat.getUser().getString("NickName"))) {//要@才会处理消息
						String reply=MsgAPI.getReply(sendMsg.replace("@" + wechat.getUser().getString("NickName"), ""),
									sendUserName.replace("@", "").substring(1, 10), wechat.getCity(),fromUserName,groupNickName,groupInf,wechat.getWxuin());
							if (null != reply) {
								this.sendMsg(wechat, reply, fromUserName);
							} else {
							}
						//}
						logger.info("group msg:[{}][{}]:{}", nickName, sendUserNickName, sendMsg.replace("<br/>", ""));
					//好友
					} else {
						
					}
				}
			}
		}
	}

	/**
	 * 发送消息
	 */
	private void sendMsg(Wechat wechat, String content, String toUserName) {
		String url = wechat.getBase_uri() + "/webwxsendmsg?" + "lang=zh_CN" + "&pass_ticket=" + wechat.getPassTicket();
		JSONObject body = new JSONObject();
		String clientMsgId = DateKit.getCurrentUnixTime() + StringKit.getRandomNumber(5);
		JSONObject msg = new JSONObject();
		msg.put("Type", 1);
		msg.put("Content", content);
		msg.put("FromUserName", wechat.getUser().getString("UserName"));
		msg.put("ToUserName", toUserName);
		msg.put("LocalID", clientMsgId);
		msg.put("ClientMsgId", clientMsgId);
		body.put("BaseRequest", wechat.getBaseRequest());
		body.put("Msg", msg);
		HttpRequest request = HttpRequest.post(url).contentType(Constant.CONTENT_TYPE)
				.header("Cookie", wechat.getCookie()).send(body.toString());
		//System.out.println("cookei:"+ wechat.getCookie());
		System.out.println("发送消息url:"+request);
		request.body();
		request.disconnect();
	}
	
	/**
	 * 获取NickName
	 */
	private String getNickName(Wechat wechat, String userName, WechatContact wechatContact) {
		JSONArray arrayContact = wechatContact.getContactList();
		String nickName = null;
		for (Object jsonObject : arrayContact) {
			JSONObject user = (JSONObject) jsonObject;
			nickName = user.getString("UserName");
			if (nickName.equals(userName)) {
				return nickName;
			}
		}
		return nickName;
	}
	public static void wxlogout(String wxno){
		//wxRobLogin.do?method=wxLogout&wxNo=
		try {
			HttpRequest logout=HttpRequest.post(Constant.ROBURL+"wxRobLogin.do?method=wxLogout&wxNo="+wxno);
			System.out.println(logout.body());
			System.out.println("后台登出...");
			
		} catch (Exception e) {
			
		}
		
	}
	
	/*获取欢迎语
	 * **/
	public static String getWelcome(String groupNickName){
		try {
			new GetGroupNickName();
			groupNickName=GetGroupNickName.getURLEncoderString(groupNickName);
			String wcDate=null;
			HttpRequest getWelcome=HttpRequest.post(Constant.ROBURL+"configManager.do?method=queryConfig&configKey=welcome&type=9&groupName="+groupNickName);
	        wcDate=getWelcome.body();
	        System.out.println(getWelcome);
	        JSONObject wec=JSONObject.parseObject(wcDate);
	        System.out.println(wec);
	    	return wec.getString("keyValue");
			
		} catch (Exception e) {
			return null;
		}
		
	}
	
}
